<template>
  <div class="create-outbound-form">
    <form @submit.prevent="submitForm">
      <!-- 客户信息 -->
      <div class="form-section">
        <h3>客户信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>客户类型 *</label>
            <select v-model="form.customerType" @change="onCustomerTypeChange" required>
              <option value="">请选择客户类型</option>
              <option value="VIP">VIP会员</option>
              <option value="Individual">散户</option>
            </select>
          </div>
          
          <div v-if="form.customerType === 'VIP'" class="form-group">
            <label>VIP客户 *</label>
            <select v-model="form.customerId" @change="onCustomerSelect" required>
              <option value="">请选择VIP客户</option>
              <option v-for="customer in vipCustomers" :key="customer.id" :value="customer.id">
                {{ customer.name }} ({{ customer.phone }})
              </option>
            </select>
          </div>
          
          <div v-if="form.customerType === 'Individual'" class="form-group">
            <label>客户姓名 *</label>
            <input v-model="form.customerName" type="text" placeholder="请输入客户姓名" required>
          </div>
          
          <div v-if="form.customerType === 'Individual'" class="form-group">
            <label>联系电话 *</label>
            <input v-model="form.customerPhone" type="tel" placeholder="请输入联系电话" required>
          </div>
          
          <div v-if="form.customerType === 'Individual'" class="form-group">
            <label>身份证号</label>
            <input v-model="form.customerIdCard" type="text" placeholder="请输入身份证号">
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="form-section">
        <h3>商品信息</h3>
        <div class="product-search">
          <div class="search-input">
            <input v-model="productSearch" type="text" placeholder="搜索商品名称或编码">
            <button type="button" @click="searchProducts">
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
        
        <div class="product-list">
          <div v-for="product in availableProducts" :key="product.id" class="product-item">
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-details">
                <span class="product-code">{{ product.code }}</span>
                <span class="product-price">¥{{ product.retailPrice }}</span>
                <span class="product-stock">库存: {{ product.stock }}</span>
              </div>
            </div>
            <button type="button" class="btn-add" @click="addProduct(product)">
              <i class="fas fa-plus"></i>
              添加
            </button>
          </div>
        </div>
      </div>

      <!-- 订单明细 -->
      <div class="form-section">
        <h3>订单明细</h3>
        <div class="order-items">
          <div v-for="(item, index) in form.items" :key="index" class="order-item">
            <div class="item-info">
              <div class="item-name">{{ item.productName }}</div>
              <div class="item-details">
                <span class="item-code">{{ item.productCode }}</span>
                <span class="item-price">¥{{ item.unitPrice }}</span>
              </div>
            </div>
            <div class="item-quantity">
              <label>数量</label>
              <input v-model.number="item.quantity" type="number" min="1" @change="updateItemTotal(index)">
            </div>
            <div class="item-discount">
              <label>折扣率</label>
              <input v-model.number="item.discountRate" type="number" min="0" max="1" step="0.01" @change="updateItemTotal(index)">
            </div>
            <div class="item-total">
              <label>小计</label>
              <span class="total-amount">¥{{ (item.itemTotalAmount || 0).toFixed(2) }}</span>
            </div>
            <button type="button" class="btn-remove" @click="removeItem(index)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 支付信息 -->
      <div class="form-section">
        <h3>支付信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>支付方式 *</label>
            <select v-model="form.paymentMethod" required>
              <option value="">请选择支付方式</option>
              <option value="Cash">现金</option>
              <option value="Card">银行卡</option>
              <option value="Mixed">混合支付</option>
            </select>
          </div>
          
          <div v-if="form.customerType === 'VIP'" class="form-group">
            <label>使用预付款</label>
            <input v-model.number="form.prepaymentUsed" type="number" min="0" :max="selectedCustomer?.prepaymentBalance || 0" @change="updatePaymentSummary">
            <span class="balance-info">可用余额: ¥{{ selectedCustomer?.prepaymentBalance || 0 }}</span>
          </div>
          
          <div v-if="form.customerType === 'VIP'" class="form-group">
            <label>使用积分</label>
            <input v-model.number="form.pointsUsed" type="number" min="0" :max="selectedCustomer?.pointsBalance || 0" @change="updatePaymentSummary">
            <span class="balance-info">可用积分: {{ selectedCustomer?.pointsBalance || 0 }}</span>
          </div>
        </div>
      </div>

      <!-- 订单汇总 -->
      <div class="form-section">
        <h3>订单汇总</h3>
        <div class="order-summary">
          <div class="summary-row">
            <span>商品总金额:</span>
            <span>¥{{ (orderSummary.totalAmount || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>折扣金额:</span>
            <span>-¥{{ (orderSummary.discountAmount || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>预付款使用:</span>
            <span>-¥{{ (orderSummary.prepaymentUsed || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>积分使用:</span>
            <span>-¥{{ (orderSummary.pointsUsed || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>税费 (13%):</span>
            <span>¥{{ (orderSummary.taxAmount || 0).toFixed(2) }}</span>
          </div>
          <div class="summary-row total">
            <span>最终金额:</span>
            <span>¥{{ (orderSummary.finalAmount || 0).toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="form-section">
        <h3>其他信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>配送地址</label>
            <textarea v-model="form.shippingAddress" placeholder="请输入配送地址"></textarea>
          </div>
          <div class="form-group">
            <label>备注</label>
            <textarea v-model="form.remark" placeholder="请输入备注信息"></textarea>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="button" class="btn-cancel" @click="$emit('close')">
          取消
        </button>
        <button type="submit" class="btn-submit" :disabled="!isFormValid">
          <i class="fas fa-save"></i>
          创建出库单
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue'

export default {
  name: 'CreateOutboundForm',
  emits: ['close', 'success'],
  setup(props, { emit }) {
    const productSearch = ref('')
    
    // 表单数据
    const form = ref({
      customerType: '',
      customerId: '',
      customerName: '',
      customerPhone: '',
      customerIdCard: '',
      items: [],
      paymentMethod: '',
      prepaymentUsed: 0,
      pointsUsed: 0,
      shippingAddress: '',
      remark: ''
    })
    
    // VIP客户列表
    const vipCustomers = ref([])
    
    // 加载VIP客户数据
    const loadVipCustomers = async () => {
      try {
        const response = await fetch('/api/customers?type=VIP&size=100', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          vipCustomers.value = data.content || []
        } else {
          console.error('加载VIP客户失败:', response.statusText)
          // 使用模拟数据作为备选
          vipCustomers.value = [
            {
              id: 1,
              name: '张三',
              phone: '13800138000',
              prepaymentBalance: 5000,
              pointsBalance: 1500
            },
            {
              id: 2,
              name: '李四',
              phone: '13900139000',
              prepaymentBalance: 3000,
              pointsBalance: 800
            }
          ]
        }
      } catch (error) {
        console.error('加载VIP客户失败:', error)
        // 使用模拟数据作为备选
        vipCustomers.value = [
          {
            id: 1,
            name: '张三',
            phone: '13800138000',
            prepaymentBalance: 5000,
            pointsBalance: 1500
          },
          {
            id: 2,
            name: '李四',
            phone: '13900139000',
            prepaymentBalance: 3000,
            pointsBalance: 800
          }
        ]
      }
    }
    
    // 可用商品列表
    const availableProducts = ref([])
    
    // 加载商品数据
    const loadProducts = async () => {
      try {
        const response = await fetch('/api/retail/products?size=50', {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          availableProducts.value = data.content || []
        } else {
          console.error('加载商品失败:', response.statusText)
          // 使用模拟数据作为备选
          availableProducts.value = [
            {
              id: 1,
              name: 'iPhone 13',
              code: 'IPHONE13',
              retailPrice: 5800,
              memberPrice: 5510,
              stock: 50
            },
            {
              id: 2,
              name: 'MacBook Pro 13寸',
              code: 'MACBOOKPRO',
              retailPrice: 9999,
              memberPrice: 9499,
              stock: 20
            },
            {
              id: 3,
              name: 'Galaxy S22',
              code: 'GALAXYS22',
              retailPrice: 5299,
              memberPrice: 5034,
              stock: 30
            },
            {
              id: 4,
              name: '男士衬衫',
              code: 'MENS_SHIRT',
              retailPrice: 199,
              memberPrice: 189,
              stock: 100
            }
          ]
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        // 使用模拟数据作为备选
        availableProducts.value = [
          {
            id: 1,
            name: 'iPhone 13',
            code: 'IPHONE13',
            retailPrice: 5800,
            memberPrice: 5510,
            stock: 50
          },
          {
            id: 2,
            name: 'MacBook Pro 13寸',
            code: 'MACBOOKPRO',
            retailPrice: 9999,
            memberPrice: 9499,
            stock: 20
          },
          {
            id: 3,
            name: 'Galaxy S22',
            code: 'GALAXYS22',
            retailPrice: 5299,
            memberPrice: 5034,
            stock: 30
          },
          {
            id: 4,
            name: '男士衬衫',
            code: 'MENS_SHIRT',
            retailPrice: 199,
            memberPrice: 189,
            stock: 100
          }
        ]
      }
    }
    
    // 选中的客户
    const selectedCustomer = ref(null)
    
    // 客户类型变化
    const onCustomerTypeChange = () => {
      form.value.customerId = ''
      form.value.customerName = ''
      form.value.customerPhone = ''
      form.value.customerIdCard = ''
      selectedCustomer.value = null
    }
    
    // 客户选择
    const onCustomerSelect = () => {
      selectedCustomer.value = (vipCustomers.value || []).find(c => c.id === form.value.customerId)
    }
    
    // 搜索商品
    const searchProducts = async () => {
      try {
        const response = await fetch(`/api/retail/products?search=${encodeURIComponent(productSearch.value)}&size=20`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          availableProducts.value = data.content || []
        } else {
          console.error('搜索商品失败:', response.statusText)
        }
      } catch (error) {
        console.error('搜索商品失败:', error)
      }
    }
    
    // 添加商品
    const addProduct = (product) => {
      const existingItem = (form.value.items || []).find(item => item.productId === product.id)
      if (existingItem) {
        existingItem.quantity += 1
        updateItemTotal(form.value.items.indexOf(existingItem))
      } else {
        const discountRate = form.value.customerType === 'VIP' ? 0.95 : 1.0
        const unitPrice = form.value.customerType === 'VIP' ? product.memberPrice : product.retailPrice
        
        form.value.items.push({
          productId: product.id,
          productName: product.name,
          productCode: product.code,
          quantity: 1,
          unitPrice: unitPrice,
          discountRate: discountRate,
          itemTotalAmount: unitPrice * discountRate
        })
      }
      updatePaymentSummary()
    }
    
    // 移除商品
    const removeItem = (index) => {
      form.value.items.splice(index, 1)
      updatePaymentSummary()
    }
    
    // 更新商品小计
    const updateItemTotal = (index) => {
      const item = form.value.items[index]
      item.itemTotalAmount = item.quantity * item.unitPrice * item.discountRate
      updatePaymentSummary()
    }
    
    // 更新支付汇总
    const updatePaymentSummary = () => {
      // 触发计算属性更新
    }
    
    // 订单汇总计算
    const orderSummary = computed(() => {
      const totalAmount = (form.value.items || []).reduce((sum, item) => sum + ((item.quantity || 0) * (item.unitPrice || 0)), 0)
      const discountAmount = (form.value.items || []).reduce((sum, item) => sum + ((item.quantity || 0) * (item.unitPrice || 0) * (1 - (item.discountRate || 0))), 0)
      const prepaymentUsed = form.value.prepaymentUsed || 0
      const pointsUsed = (form.value.pointsUsed || 0) * 0.01 // 1积分 = 0.01元
      const subtotal = totalAmount - discountAmount - prepaymentUsed - pointsUsed
      const taxAmount = subtotal * 0.13
      const finalAmount = subtotal + taxAmount
      
      return {
        totalAmount,
        discountAmount,
        prepaymentUsed,
        pointsUsed,
        taxAmount,
        finalAmount
      }
    })
    
    // 表单验证
    const isFormValid = computed(() => {
      return form.value.customerType && 
             form.value.items.length > 0 && 
             form.value.paymentMethod &&
             (form.value.customerType === 'VIP' ? form.value.customerId : form.value.customerName)
    })
    
    // 提交表单
    const submitForm = async () => {
      try {
        const orderData = {
          ...form.value,
          totalAmount: orderSummary.value.totalAmount,
          discountAmount: orderSummary.value.discountAmount,
          taxAmount: orderSummary.value.taxAmount,
          finalAmount: orderSummary.value.finalAmount,
          pointsEarned: Math.floor(orderSummary.value.finalAmount * 0.01), // 1%积分
          orderDate: new Date().toISOString(),
          status: 'Pending'
        }
        
        const response = await fetch('/api/retail/orders', {
          method: 'POST',
          headers: { 
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: JSON.stringify(orderData)
        })
        
        if (response.ok) {
          const result = await response.json()
          console.log('创建出库单成功:', result)
          alert('出库单创建成功！')
          emit('success')
        } else {
          let errorMessage = response.statusText
          try {
            const errorData = await response.json()
            errorMessage = errorData.message || errorData.error || response.statusText
            console.error('创建出库单失败:', errorData)
          } catch (parseError) {
            console.error('解析错误响应失败:', parseError)
            console.error('响应状态:', response.status, response.statusText)
          }
          alert(`创建出库单失败: ${errorMessage}`)
        }
      } catch (error) {
        console.error('创建出库单失败:', error)
        alert('创建出库单失败，请检查网络连接')
      }
    }
    
    return {
      productSearch,
      form,
      vipCustomers,
      availableProducts,
      selectedCustomer,
      orderSummary,
      isFormValid,
      onCustomerTypeChange,
      onCustomerSelect,
      searchProducts,
      addProduct,
      removeItem,
      updateItemTotal,
      updatePaymentSummary,
      submitForm,
      loadVipCustomers,
      loadProducts
    }
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadVipCustomers()
      loadProducts()
    })
  }
}
</script>

<style scoped>
.create-outbound-form {
  max-width: 800px;
  margin: 0 auto;
}

.form-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
}

.form-section h3 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e2e8f0;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: 500;
  color: #4a5568;
  font-size: 0.875rem;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 0.875rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

.balance-info {
  font-size: 0.75rem;
  color: #718096;
  margin-top: 4px;
}

.product-search {
  margin-bottom: 16px;
}

.search-input {
  display: flex;
  gap: 8px;
}

.search-input input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.search-input button {
  padding: 10px 16px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.product-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 4px;
}

.product-details {
  display: flex;
  gap: 12px;
  font-size: 0.875rem;
  color: #718096;
}

.btn-add {
  padding: 6px 12px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.order-item {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr auto;
  gap: 12px;
  align-items: center;
  padding: 16px;
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.item-name {
  font-weight: 500;
  color: #2d3748;
}

.item-details {
  display: flex;
  gap: 12px;
  font-size: 0.875rem;
  color: #718096;
}

.item-quantity input,
.item-discount input {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  text-align: center;
}

.item-total {
  text-align: right;
}

.total-amount {
  font-weight: 600;
  color: #2d3748;
  font-size: 1.1rem;
}

.btn-remove {
  padding: 6px;
  background: #fed7d7;
  color: #742a2a;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.order-summary {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 16px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.summary-row.total {
  font-weight: 600;
  font-size: 1.1rem;
  color: #2d3748;
  border-bottom: none;
  border-top: 2px solid #e2e8f0;
  margin-top: 8px;
  padding-top: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px 0;
}

.btn-cancel,
.btn-submit {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #e2e8f0;
  color: #4a5568;
}

.btn-submit {
  background: #667eea;
  color: white;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-cancel:hover,
.btn-submit:hover:not(:disabled) {
  transform: translateY(-1px);
}

@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .order-item {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .product-list {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>
